<?php

namespace app\admin\controller\coll;

use app\common\controller\Backend;
use think\Db;
use app\common\model\coll\Analysis;
use app\common\model\coll\Pay;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Log extends Backend
{
    
    /**
     * Log模型对象
     * @var \app\common\model\coll\Log
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\coll\Log;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $this->handlefilter();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['storehouse','pay'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                ->with(['storehouse','pay'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','price','analysis_id','image','remark','is_income','createtime','operator','company','pay_time','status','handler']);
                $row->visible(['storehouse']);
                $row->getRelation('storehouse')->visible(['name']);
                $row->visible(['pay']);
                $row->getRelation('pay')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $status =$this->model->is_income_type();
            foreach ($list as $k=> $v){
                $list[$k]['is_income'] = $status[$list[$k]['is_income']];
                $arr = explode(',',$v['analysis_id']);
                $arow = Db::name('analysis')->where(array('id'=>$arr[0]))->find();
                $list[$k]['settle_name'] = $arow['settle_name'];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function edit($ids=null){
        $row = $this->model->find($ids);
        if($this->request->isAjax()){
            if(empty($row)){
                $this->error('单据不存在');
            }
            if($row['status'] != 1){
                $this->error('单据状态异常');
            }
            $pay_id = input('pay_id/d',0);
            $res = $this->model->save(array('pay_id'=>$pay_id),array('id'=>$ids));
            if($res){
                $this->success('修改成功');
            }else{
                $this->error('修改失败');
            }
        }


        $types = $this->model->is_income_type();
        $pays = Pay::select();

        $row['is_income'] = $types[$row['is_income']];
        $imgs = explode(',',$row['image']);
        $this->assign('imgs',$imgs);
        $this->assign('pays',$pays);
        $this->assign('row',$row);
        return $this->view->fetch();
    }
    public function detail($ids=null){
        $row = $this->model->find($ids);
        $types = $this->model->is_income_type();
        $pays = Pay::find($row['pay_id']);
        $row['is_income'] = $types[$row['is_income']];
        $imgs = explode(',',$row['image']);
        $ans =Db::name('analysis')->where(array('id'=>array('in',$row['analysis_id'])))->select();
        $dill_type = dill_type();
        foreach ($ans as &$v){
            $v['source'] = $dill_type[$v['source']];
        }


        $this->assign('ans',$ans);
        $this->assign('imgs',$imgs);
        $this->assign('pays',$pays);
        $this->assign('row',$row);
        return $this->view->fetch();
    }
    public function cancelbill($ids=null){
        $reason = input('reason');
        $row = $this->model->find($ids);
        if($row['status'] !=1){
            $this->error('状态异常');
        }
        $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
        Db::startTrans();
        try {
            $this->model->save(array('status' => 2), array('id' => $ids));
            $res =Db::name('cancel_bill')
                ->insert(array(
                    'reason' => $reason,
                    'source' => 14,
                    'admin_id' => session('admin')['id'],
                    'group_id' => $group['group_id'],
                    'company' => $group['name'],
                    'operator' => session('admin')['nickname'],
                    'controller' => 'coll/log',
                    'source_id' => $row['id'],
                    'number' => isset($row['number'])?$row['number']:'',
                    'createtime' => time(),
                ));
//            $analysis = new Analysis();
//            $arow = $analysis->find($row['analysis_id']);
            $analysis_ids = explode(',',$row['analysis_id']);
            foreach ($analysis_ids as $v){
                $count = $this->model->where('find_in_set('.$v.',analysis_id)')->where('status',1)->count();
                if($count > 0){
                    $analysis = new Analysis();
                    $analysis->save(array('status'=>2),array('id'=>$v));
                }else{
                    $analysis = new Analysis();
                    $analysis->save(array('status'=>1),array('id'=>$v));
                }
            }
            $id = $row['analysis_id'];
            $where[] = ['exp',Db::raw("FIND_IN_SET($id,category)")];
            $where[] =array('status'=>1);



            Db::commit();
            return array(
                'code'=>1,
                'msg'=>'操作成功'
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
}
